<template>
  <BasicModal centered destroyOnClose
              v-bind="$attrs"
              :width="720"
              :bodyStyle="{overflowY:'hidden', height:'585px'}"
              :title="title"
              :canFullscreen="false"
              :maskClosable="false"
              @ok="handleOk"
              @register="registerModal"
  >
    <a-row :gutter="5" style="margin: 0; padding: 0">
      <a-col flex="248px" style="border: 1px #ddd solid;">
        <CustomerTree @onClick="onClick"/>
      </a-col>
      <a-col flex="455px" style="border: 1px #ddd solid; padding-top: 10px; margin-left: 5px">
        <a-form ref="registerForm" :model="model" :rules="validatorRules" :labelCol="{ span: 5 }" :wrapperCol="{ span: 17 }">
          <a-input type="hidden" v-model:value="model.id" />
          <a-form-item name="type" label="数据类型">
            <a-radio-group v-model:value="indexRegisterType" buttonStyle="solid" >
              <a-radio-button :value="TypeEnum.CITE" :disabled="indexRegisterType != TypeEnum.CITE">资方</a-radio-button>
              <a-radio-button :value="TypeEnum.COMP" :disabled="indexRegisterType != TypeEnum.COMP">产品</a-radio-button>
              <a-radio-button :value="TypeEnum.PERS" :disabled="indexRegisterType != TypeEnum.PERS">等级</a-radio-button>
            </a-radio-group>
          </a-form-item>
          <a-form-item name="parentId" label="上级编号" v-show="items.type_kh || items.type_lxr">
            <a-input disabled class="formText" v-model:value="model.parentId" />
          </a-form-item>
          <a-form-item name="parentId" label="上级名称" v-show="items.type_kh || items.type_lxr">
            <a-input readonly class="formText" v-model:value="model.parentAreaName" />
          </a-form-item>
          <a-form-item name="areaName" :label="items.customerText" v-show="items.type_cs || items.type_kh || items.type_lxr">
            <a-input type="text" class="formText w-280px" v-model:value="model.areaName" autoComplete="off"/>
          </a-form-item>
          <a-form-item label="排序">
            <a-input type="number" class="w-150px" v-model:value="model.sort" :maxlength="5"/>
          </a-form-item>
        </a-form>
      </a-col>
    </a-row>
  </BasicModal>
</template>

<script lang="ts" setup>
import { computed, inject, nextTick, reactive, ref, unref } from "vue";
import { BasicModal, useModalInner } from "/@/components/Modal";
import { customerSave, getCustomerById, TypeEnum } from "../customer.api";
import { ValidateErrorEntity } from "ant-design-vue/es/form/interface";
import { useUserStore } from '/@/store/modules/user';
import CustomerTree from "./CustomerTree.vue"

const emit = defineEmits(["success", "register"]);
//接收表单对象
const registerForm = ref();
//表单控件
const items = reactive({
  type_cs: false,
  type_kh: false,
  type_lxr: true,
  customerText: "上级名称",
  action:'',
});

//是否为更新操作
const isUpdate = ref<boolean>(false);
const title = computed(() => isUpdate.value ? "编辑" : "新增");

//表单数据
let model = reactive<any>({});
//数据类型，默认值
let indexRegisterType = ref<string>('1');

//自定义
// let validateDepartId = async (rule, value) => {
//   console.info("validateDepartId@@@", model.type, rule, value)
//   if (model.type === '2' && !value) {
//     return Promise.reject('不能为空!');
//   } else {
//     return Promise.resolve();
//   }
// };

//表单校验
const validatorRules = reactive<any>({
  type: [{ required: true, message: "不能为空!" }],
  parentId: [{ required: true, message: "不能为空!" }],
  areaName: [{ required: true, message: "不能为空!" }],
  lxdh: [{ required: true, message: "不能为空!", trigger: 'blur' }],
});

/**
 * 定义组件变量
 */
const [registerModal, { setModalProps, closeModal }] = useModalInner(async data => {
  setModalProps({ confirmLoading: false });
  resetFields()
  isUpdate.value = !!data?.isUpdate;
  let typeVal = 1;
  if (unref(isUpdate)) {
    //获取详情
    await getCustomerById({ id: data.record.id }).then((res) => {
      let name = res.pathName.split("|")
      res.parentAreaName = name[name.length - 2] || ''
      //表单赋值
      Object.assign(model, res);
      typeVal = Number(model.type)
    });
  }
  await changeType(typeVal)
});

//表单重置
function resetFields() {
  model.id = null;
  model.type = '';
  model.parentId = '';
  model.parentAreaName = '';
  model.areaName = '';
  model.sort = '';
}

// 提交事件 registerForm.value.
//const registerForm = ref();

async function handleOk() {
  await registerForm.value.validate().then(async () => {
    try {
      setModalProps({ confirmLoading: true });
      //提交表单
      await customerSave(items.action, model);
      closeModal();
      emit("success");
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }).catch((error: ValidateErrorEntity<any>) => {
    console.log("error", error);
  });
}

/**
 * 树节点点击事件
 * 当点城市 type = 0, 加1后 customer.type = 1 公司
 * @param treeNode
 * @returns {boolean}
 */
function onClick(treeNode) {
  var id = model.id;
  var dataVal = (Number(model.type) + 1);
  var typeVal = (Number(treeNode.type) + 1);     //点选节点属性
  //id有值时为更新，无时为添加
  if (id) {
    if (!dataVal) {
      console.info("dataVal = " + dataVal + ", 数据不符合规范，请检查。");
      return false;
    }
    //当前是地区  dataVal=1，上级目录不可变更
    //当前是公司  dataVal=2，上级目录只可变更到，地区下
    //当前是联系  dataVal=3，上级目录只可变更到，公司下
    //点选的要小于编辑的
    if (dataVal == 1 || (dataVal != (typeVal + 1))) {
      return false;
    }
  } else {

  }

  if (typeVal != undefined && typeVal != null && typeVal >= 0) {
    if (typeVal == 0) {
      // 添加城市
      model.type = typeVal;
      model.parentId = "";
      model.parentAreaName = "";
      changeType(typeVal);
    } else if (typeVal == 1) {
      // 添加公司
      model.type = typeVal;
      model.parentId = treeNode.id;
      model.parentAreaName = treeNode.name;
      changeType(typeVal);
    } else if (typeVal == 2) {
      // 添加联系人
      model.type = typeVal;
      model.parentId = treeNode.id;
      model.parentAreaName = treeNode.name;
      changeType(typeVal);
    } else if (typeVal == 3) {
      model.parentId = "";
      model.parentAreaName = "";
      model.areaName = "";
    }
  }
}

function changeType(typeVal: number) {
  //alert($("#searchBoxx").val());
  model.type = typeVal;
  indexRegisterType.value = typeVal + ""
  //$("#searchBoxx").attr("disabled",true);
  if (typeVal == 0) {
    validatorRules.type[0].required = false;
    validatorRules.parentId[0].required = false;
    items.customerText = "资方名称：";
    items.type_kh  = false;
    items.type_lxr = false;
    items.type_cs  = true;
    items.action = "/customer/saveCity";
  } else if (typeVal == 1) {
    validatorRules.type[0].required = true;
    validatorRules.parentId[0].required = true;
    items.customerText = "产品名称：";
    items.type_cs  = false;
    items.type_lxr = false;
    items.type_kh  = true;
    items.action = "/customer/saveDirectory";
  } else if (typeVal == 2) {
    validatorRules.type[0].required = true;
    validatorRules.parentId[0].required = true;
    items.customerText = "等级名称：";
    items.type_cs  = false;
    items.type_kh  = false;
    items.type_lxr = true;
    items.action = "/customer/save";
  }
}

</script>

<style scoped lang="less">

.jeecg-basic-tree {
  border: 1px green solid;
  overflow: auto;

  ::v-deep(.ant-tree) {
    li {
      padding: 0 !important;
    }
  }
}

</style>
